from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *
from django.core.paginator import Paginator


class CateView(APIView):  # 分类的增删改查
    def post(self, request):
        if CateModel.objects.filter(name=request.data.get('name')):
            return Response({'msg': '该分类已存在', 'code': 400})
        ser = CateSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            print(ser.errors)
            return Response({'msg': '添加失败', 'code': 400})

    def get(self, request,pid):
        cate_obj=CateModel.objects.all()
        page_fy=Paginator(cate_obj,3)
        paged=page_fy.page(pid)
        ser=CateSer(paged,many=True)
        return Response({
            'page_sum':page_fy.num_pages,
            'page_list':[i for i in page_fy.page_range],
            'data':ser.data
        })


    def put(self, request,cid):
        cate_obj=CateModel.objects.filter(pk=cid).first()
        ser=CateSer(cate_obj,request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '修改成功', 'code': 200})
        else:
            print(ser.errors)
            return Response({'msg': '修改失败', 'code': 400})

    def delete(self, request,cid):
        cate_obj = CateModel.objects.filter(pk=cid).first()
        if cate_obj:
            cate_obj.delete()
            return Response({'msg': '删除成功', 'code': 200})
        else:
            return Response({'msg': '删除失败', 'code': 200})


class BoodsView(APIView):  # 书籍的增删改查
    def post(self, request):
        if BooksModel.objects.filter(name=request.data.get('name')):
            return Response({'msg': '该书籍已存在', 'code': 400})
        ser = BooksSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            print(ser.errors)
            return Response({'msg': '添加失败', 'code': 400})

    def get(self, request,cid):
        cate_obj=CateModel.objects.get(pk=cid)
        boods_obj=BooksModel.objects.filter(cate=cate_obj)
        ser=BooksSer(boods_obj,many=True)
        return Response(ser.data)



    def put(self, request,bid):
        boods_obj=BooksModel.objects.filter(pk=bid).first()
        ser=BooksSer(boods_obj,request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '修改成功', 'code': 200})
        else:
            print(ser.errors)
            return Response({'msg': '修改失败', 'code': 400})

    def delete(self, request,bid):
        boods_obj = BooksModel.objects.filter(pk=bid).first()
        if boods_obj:
            boods_obj.delete()
            return Response({'msg': '删除成功', 'code': 200})
        else:
            return Response({'msg': '删除失败', 'code': 200})